package com.laycoding.layrpc.common;

import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class LayRpcRegistryCache {
    public static ConcurrentHashMap<Channel,String> map = new ConcurrentHashMap<>();

    private static AtomicInteger number = new AtomicInteger(1);

    public static Channel getChannel(String name) {
        Set<Map.Entry<Channel,String>> entries = map.entrySet();
        for (Map.Entry<Channel,String> entry : entries) {
           if (entry.getValue().equals(name)) {
               return entry.getKey().isActive() ? entry.getKey() : null;
           }
        }
        return null;
    }

    public static void putChannel(Channel channel,String name){
       map.put(channel,name);
    }
    public static void removeChannel(Channel channel){
        if (map.containsKey(channel)){
            map.remove(channel);
        }
    }
    public static void CloseAll(){
        ConcurrentHashMap.KeySetView<Channel, String> channels = map.keySet();
        for (Channel channel : channels) {
            if (channel.isActive()) {
                channel.close();
            }
        }
    }
}
